Bayesian GLM Part5

Author

Murray Logan

Published

28/07/2023

1 Preparations

Load the necessary libraries

library(tidyverse)  #for data wrangling etc
library(rstanarm)   #for fitting models in STAN
library(cmdstanr)   #for cmdstan
library(brms)       #for fitting models in STAN
library(standist)   #for exploring distributions
library(HDInterval) #for HPD intervals
library(posterior)  #for posterior draws
library(coda)       #for diagnostics
library(ggmcmc)     #for MCMC diagnostics
library(bayesplot)  #for diagnostics
library(rstan)      #for interfacing with STAN
library(DHARMa)     #for residual diagnostics
library(emmeans)    #for marginal means etc
library(broom)      #for tidying outputs
library(broom.mixed)#for summarising models
library(tidybayes)  #for more tidying outputs
library(ggeffects)  #for partial plots
library(tidyverse)  #for data wrangling etc
library(patchwork)  #for multi-panel figures
library(ggridges)   #for ridge plots
library(bayestestR) #for ROPE
library(see)        #for some plots
library(easystats)  #for the easystats ecosystem
source('helperFunctions.R')

2 Scenario

Here is a modified example from Quinn and Keough (2002). Day and Quinn (1989) described an experiment that examined how rock surface type affected the recruitment of barnacles to a rocky shore. The experiment had a single factor, surface type, with 4 treatments or levels: algal species 1 (ALG1), algal species 2 (ALG2), naturally bare surfaces (NB) and artificially scraped bare surfaces (S). There were 5 replicate plots for each surface type and the response (dependent) variable was the number of newly recruited barnacles on each plot after 4 weeks.

Figure 1: Six-plated barnacle
Table 1: Format of day.csv data files
TREAT BARNACLE
ALG1 27
.. ..
ALG2 24
.. ..
NB 9
.. ..
S 12
.. ..
Table 2: Description of the variables in the day data file
TREAT Categorical listing of surface types. ALG1 = algal species 1, ALG2 = algal species 2, NB = naturally bare surface, S = scraped bare surface.
BARNACLE The number of newly recruited barnacles on each plot after 4 weeks.

3 Read in the data

day <- read_csv('../public/data/day.csv', trim_ws = TRUE)
Rows: 20 Columns: 2
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): TREAT
dbl (1): BARNACLE

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
glimpse(day)
Rows: 20
Columns: 2
$ TREAT    <chr> "ALG1", "ALG1", "ALG1", "ALG1", "ALG1", "ALG2", "ALG2", "ALG2…
$ BARNACLE <dbl> 27, 19, 18, 23, 25, 24, 33, 27, 26, 32, 9, 13, 17, 14, 22, 12…
## Explore the first 6 rows of the data
head(day)
# A tibble: 6 × 2
  TREAT BARNACLE
  <chr>    <dbl>
1 ALG1        27
2 ALG1        19
3 ALG1        18
4 ALG1        23
5 ALG1        25
6 ALG2        24
str(day)
spc_tbl_ [20 × 2] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ TREAT   : chr [1:20] "ALG1" "ALG1" "ALG1" "ALG1" ...
 $ BARNACLE: num [1:20] 27 19 18 23 25 24 33 27 26 32 ...
 - attr(*, "spec")=
  .. cols(
  ..   TREAT = col_character(),
  ..   BARNACLE = col_double()
  .. )
 - attr(*, "problems")=<externalptr> 
day |> datawizard::data_codebook()
day (20 rows and 2 variables, 2 shown)

ID | Name     | Type      | Missings |  Values |         N
---+----------+-----------+----------+---------+----------
1  | TREAT    | character | 0 (0.0%) |    ALG1 | 5 (25.0%)
   |          |           |          |    ALG2 | 5 (25.0%)
   |          |           |          |      NB | 5 (25.0%)
   |          |           |          |       S | 5 (25.0%)
---+----------+-----------+----------+---------+----------
2  | BARNACLE | numeric   | 0 (0.0%) | [8, 33] |        20
----------------------------------------------------------

Start by declaring the categorical variables as factor.

day <- day |> mutate(TREAT = factor(TREAT))

Model formula: \[ \begin{align} y_i &\sim{} \mathcal{Pois}(\lambda_i)\\ ln(\mu_i) &= \boldsymbol{\beta} \bf{X_i}\\ \beta_0 &\sim{} \mathcal{N}(3.1, 1)\\ \beta_{1,2,3} &\sim{} \mathcal{N}(0,1)\\ \end{align} \]

where \(\boldsymbol{\beta}\) is a vector of effects parameters and \(\bf{X}\) is a model matrix representing the intercept and treatment contrasts for the effects of Treatment on barnacle recruitment.

4 Exploratory data analysis

The exploratory data analyses that we performed in the frequentist instalment of this example are equally valid here. That is, boxplots and/or violin plots for each population (substrate type).

day |> ggplot(aes(y = BARNACLE, x = TREAT)) +
    geom_boxplot()+
    geom_point(color = 'red')

day |> ggplot(aes(y = BARNACLE, x = TREAT)) +
    geom_violin()+
    geom_point(color = 'red')

Conclusions:

  • although exploratory data analysis suggests that we might well be fine modelling these data against a Gaussian distribution, a Poisson distribution would clearly be a more natural choice and it would also prevent any non positive predictions.

5 Fit the model

In rstanarm, the default priors are designed to be weakly informative. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.

day.rstanarm = stan_glm(BARNACLE ~ TREAT, data=day,
                        family=poisson(link='log'), 
                         iter = 5000, warmup = 1000,
                         chains = 3, thin = 5, refresh = 0)
prior_summary(day.rstanarm)
Priors for model 'day.rstanarm' 
------
Intercept (after predictors centered)
 ~ normal(location = 0, scale = 2.5)

Coefficients
  Specified prior:
    ~ normal(location = [0,0,0], scale = [2.5,2.5,2.5])
  Adjusted prior:
    ~ normal(location = [0,0,0], scale = [5.63,5.63,5.63])
------
See help('prior_summary.stanreg') for more details

This tells us:

  • for the intercept, when the family is Poisson, it is using a normal prior with a mean of 0 and a standard deviation of 2.5. The 2.5 is used for all intercepts. It is often scaled, but only if it is larger than 2.5 is the scaled version kept.

  • for the coefficients (in this case, just the slope), the default prior is a normal prior centred around 0 with a standard deviation of 2.5. This is then adjusted for the scale of the data by dividing the 2.5 by the standard deviation of the numerical dummy variables for the predictor (then rounded).

2.5/sd(model.matrix(~TREAT, day)[, 2])
[1] 5.627314
  • there is no auxiliary prior as we are employing a Poisson distribution.

One way to assess the priors is to have the MCMC sampler sample purely from the prior predictive distribution without conditioning on the observed data. Doing so provides a glimpse at the range of predictions possible under the priors. On the one hand, wide ranging predictions would ensure that the priors are unlikely to influence the actual predictions once they are conditioned on the data. On the other hand, if they are too wide, the sampler is being permitted to traverse into regions of parameter space that are not logically possible in the context of the actual underlying ecological context. Not only could this mean that illogical parameter estimates are possible, when the sampler is traversing regions of parameter space that are not supported by the actual data, the sampler can become unstable and have difficulty.

We can draw from the prior predictive distribution instead of conditioning on the response, by updating the model and indicating prior_PD=TRUE. After refitting the model in this way, we can plot the predictions to gain insights into the range of predictions supported by the priors alone.

day.rstanarm1 <- update(day.rstanarm,  prior_PD=TRUE)
day.rstanarm1 |>
    ggpredict() |>
    plot(add.data = TRUE)
$TREAT

ggpredict(day.rstanarm1) |>
    plot(add.data=TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

Conclusions:

  • we see that the range of predictions is fairly wide and the predicted means could range from 0 to very large (perhaps too large).

The following link provides some guidance about defining priors. [https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations]

When defining our own priors, we typically do not want them to be scaled.

If we wanted to define our own priors that were less vague, yet still not likely to bias the outcomes, we could try the following priors (mainly plucked out of thin air):

  • \(\beta_0\): normal centred at 3 with a standard deviation of 10
    • mean of 3: since mean(log(day$BARNACLE))
    • sd of 1: since sd(log(day$BARNACLE))
  • \(\beta_1\): normal centred at 0 with a standard deviation of 6
    • sd of 1: since: sd(log(day$BARNACLE))/apply(model.matrix(~TREAT, data = day), 2, sd)

I will also overlay the raw data for comparison.

day.rstanarm2 <- stan_glm(BARNACLE ~ TREAT, data=day,
                        family=poisson(link='log'), 
                         prior_intercept = normal(3, 1, autoscale=FALSE),
                         prior = normal(0, 1, autoscale=FALSE),
                         prior_PD=TRUE, 
                         iter = 5000, warmup = 1000,
                         chains = 3, thin = 5, refresh = 0
                         )
ggpredict(day.rstanarm2) |>
  plot(add.data=TRUE, log.y = TRUE)
$TREAT

Now lets refit, conditioning on the data.

day.rstanarm3= update(day.rstanarm2,  prior_PD=FALSE) 
posterior_vs_prior(day.rstanarm3, color_by='vs', group_by=TRUE,
                   facet_args=list(scales='free_y'))

Drawing from prior...

Conclusions:

  • in each case, the prior is substantially wider than the posterior, suggesting that the posterior is not biased towards the prior.
ggpredict(day.rstanarm3) |> plot(add.data=TRUE)
$TREAT

In brms, the default priors are designed to be weakly informative. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.

Unlike rstanarm, brms models must be compiled before they start sampling. For most models, the compilation of the stan code takes around 45 seconds.

day.form <- bf(BARNACLE ~ TREAT,
               family = poisson(link = 'log'))
day.brm <- brm(day.form, 
               data = day,
               iter = 5000,
               warmup = 2500,
               chains = 3, cores = 3,
               thin = 5,
               refresh = 0,
               backend = "cmdstan")
Start sampling
Running MCMC with 3 parallel chains...

Chain 1 finished in 0.1 seconds.
Chain 2 finished in 0.1 seconds.
Chain 3 finished in 0.1 seconds.

All 3 chains finished successfully.
Mean chain execution time: 0.1 seconds.
Total execution time: 0.3 seconds.
day.brm |> prior_summary()
                prior     class      coef group resp dpar nlpar lb ub       source
               (flat)         b                                            default
               (flat)         b TREATALG2                             (vectorized)
               (flat)         b   TREATNB                             (vectorized)
               (flat)         b    TREATS                             (vectorized)
 student_t(3, 3, 2.5) Intercept                                            default

This tells us:

  • for the intercept, it is using a student t (flatter normal) prior with a mean of 0 and a standard deviation of 2.5. These mean and standard deviation values are the defaults.

  • for the beta coefficients (in this case, each effect), the default prior is a improper flat prior. A flat prior essentially means that any value between negative infinity and positive infinity are equally likely. Whilst this might seem reckless, in practice, it seems to work reasonably well for non-intercept beta parameters.

  • since we have nominated a Poisson distribution, there is no auxiliary prior.

day.brm1 |> ggpredict() |> plot(add.data=TRUE)
$TREAT

day.brm1 |>
    ggpredict() |>
    plot(add.data=TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

## day.brm1 |> ggpredict() |> plot(add.data=TRUE) |> `[[`(1) + scale_y_log10()
day.brm1 |>
    ggemmeans(~TREAT) |>
    plot(add.data=TRUE) +
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

day.brm1 |> 
    conditional_effects() |>
    plot(points=TRUE)

day.brm1 |>
    conditional_effects() |>
    plot(points=TRUE) |>
    wrap_plots() &
    scale_y_log10()

Conclusions:

  • we see that the range of predictions is fairly wide (ranging from 0 to very high)
day.brm2 |> ggpredict() |> plot(add.data=TRUE)
$TREAT

day.brm2 |>
    ggpredict() |>
    plot(add.data=TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

day.brm2 |> ggemmeans(~TREAT) |> plot(add.data=TRUE)

day.brm2 |>
    ggemmeans(~TREAT) |>
    plot(add.data=TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

day.brm2 |> conditional_effects() |>  plot(points=TRUE)

day.brm2 |>
    conditional_effects() |>
    plot(points=TRUE) |>
    wrap_plots() &
    scale_y_log10()

day.brm3 <- day.brm2 |> update(sample_prior = 'yes', refresh = 0) 
The desired updates require recompiling the model
Start sampling
Running MCMC with 3 sequential chains...

Chain 1 finished in 0.1 seconds.
Chain 2 finished in 0.1 seconds.
Chain 3 finished in 0.1 seconds.

All 3 chains finished successfully.
Mean chain execution time: 0.1 seconds.
Total execution time: 0.5 seconds.
day.brm3 |> get_variables()
 [1] "b_Intercept"     "b_TREATALG2"     "b_TREATNB"       "b_TREATS"       
 [5] "prior_Intercept" "prior_b"         "lprior"          "lp__"           
 [9] "accept_stat__"   "treedepth__"     "stepsize__"      "divergent__"    
[13] "n_leapfrog__"    "energy__"       
day.brm3 |> hypothesis('TREATALG2<0') |> plot()

day.brm3 |> hypothesis('TREATNB<0') |> plot()

day.brm3 |> hypothesis('TREATS<0') |> plot()

day.brm3 |> SUYR_prior_and_posterior()

day.brm3 |> standata()
$N
[1] 20

$Y
 [1] 27 19 18 23 25 24 33 27 26 32  9 13 17 14 22 12  8 15 20 11

$K
[1] 4

$X
   Intercept TREATALG2 TREATNB TREATS
1          1         0       0      0
2          1         0       0      0
3          1         0       0      0
4          1         0       0      0
5          1         0       0      0
6          1         1       0      0
7          1         1       0      0
8          1         1       0      0
9          1         1       0      0
10         1         1       0      0
11         1         0       1      0
12         1         0       1      0
13         1         0       1      0
14         1         0       1      0
15         1         0       1      0
16         1         0       0      1
17         1         0       0      1
18         1         0       0      1
19         1         0       0      1
20         1         0       0      1
attr(,"assign")
[1] 0 1 1 1
attr(,"contrasts")
attr(,"contrasts")$TREAT
     ALG2 NB S
ALG1    0  0 0
ALG2    1  0 0
NB      0  1 0
S       0  0 1


$prior_only
[1] 0

attr(,"class")
[1] "standata" "list"    
day.brm3 |> stancode()
// generated with brms 2.19.0
functions {
  
}
data {
  int<lower=1> N; // total number of observations
  array[N] int Y; // response variable
  int<lower=1> K; // number of population-level effects
  matrix[N, K] X; // population-level design matrix
  int prior_only; // should the likelihood be ignored?
}
transformed data {
  int Kc = K - 1;
  matrix[N, Kc] Xc; // centered version of X without an intercept
  vector[Kc] means_X; // column means of X before centering
  for (i in 2 : K) {
    means_X[i - 1] = mean(X[ : , i]);
    Xc[ : , i - 1] = X[ : , i] - means_X[i - 1];
  }
}
parameters {
  vector[Kc] b; // population-level effects
  real Intercept; // temporary intercept for centered predictors
}
transformed parameters {
  real lprior = 0; // prior contributions to the log posterior
  lprior += normal_lpdf(b | 0, 2.4);
  lprior += normal_lpdf(Intercept | 3.1, 2.2);
}
model {
  // likelihood including constants
  if (!prior_only) {
    target += poisson_log_glm_lpmf(Y | Xc, Intercept, b);
  }
  // priors including constants
  target += lprior;
}
generated quantities {
  // actual population-level intercept
  real b_Intercept = Intercept - dot_product(means_X, b);
  // additionally sample draws from priors
  real prior_b = normal_rng(0, 2.4);
  real prior_Intercept = normal_rng(3.1, 2.2);
}

6 MCMC sampling diagnostics

The bayesplot package offers a range of MCMC diagnostics as well as Posterior Probability Checks (PPC), all of which have a convenient plot() interface. Lets start with the MCMC diagnostics.

See list of available diagnostics by name
available_mcmc()
bayesplot MCMC module:
  mcmc_acf
  mcmc_acf_bar
  mcmc_areas
  mcmc_areas_ridges
  mcmc_combo
  mcmc_dens
  mcmc_dens_chains
  mcmc_dens_overlay
  mcmc_hex
  mcmc_hist
  mcmc_hist_by_chain
  mcmc_intervals
  mcmc_neff
  mcmc_neff_hist
  mcmc_nuts_acceptance
  mcmc_nuts_divergence
  mcmc_nuts_energy
  mcmc_nuts_stepsize
  mcmc_nuts_treedepth
  mcmc_pairs
  mcmc_parcoord
  mcmc_rank_ecdf
  mcmc_rank_hist
  mcmc_rank_overlay
  mcmc_recover_hist
  mcmc_recover_intervals
  mcmc_recover_scatter
  mcmc_rhat
  mcmc_rhat_hist
  mcmc_scatter
  mcmc_trace
  mcmc_trace_highlight
  mcmc_violin

Of these, we will focus on:

  • mcmc_trace: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different shade of blue, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
plot(day.rstanarm3, plotfun='mcmc_trace')

The chains appear well mixed and very similar

  • acf (auto-correlation function): plots the auto-correlation between successive MCMC sample lags for each parameter and each chain
plot(day.rstanarm3, 'acf_bar')
Warning: The `facets` argument of `facet_grid()` is deprecated as of ggplot2 2.2.0.
ℹ Please use the `rows` argument instead.
ℹ The deprecated feature was likely used in the bayesplot package.
  Please report the issue at <https://github.com/stan-dev/bayesplot/issues/>.

There is no evidence of auto-correlation in the MCMC samples

  • Rhat: Rhat is a measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
plot(day.rstanarm3, 'rhat_hist')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

All Rhat values are below 1.05, suggesting the chains have converged.

  • neff (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

plot(day.rstanarm3, 'neff_hist')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Ratios all very high.

More diagnostics
plot(day.rstanarm3, 'combo')

plot(day.rstanarm3, 'violin')

The rstan package offers a range of MCMC diagnostics. Lets start with the MCMC diagnostics.

Of these, we will focus on:

  • stan_trace: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different colour, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
stan_trace(day.rstanarm3)

The chains appear well mixed and very similar

  • stan_acf (autocorrelation function): plots the autocorrelation between successive MCMC sample lags for each parameter and each chain
stan_ac(day.rstanarm3) 

There is no evidence of auto-correlation in the MCMC samples

  • stan_rhat: Rhat is a scale reduction factor measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
stan_rhat(day.rstanarm3) 
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

All Rhat values are below 1.05, suggesting the chains have converged.

  • stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

stan_ess(day.rstanarm3)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Ratios all very high.

stan_dens(day.rstanarm3, separate_chains = TRUE)

The ggmean package also has a set of MCMC diagnostic functions. Lets start with the MCMC diagnostics.

Of these, we will focus on:

  • ggs_traceplot: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different colour, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
day.ggs <- ggs(day.rstanarm3)
ggs_traceplot(day.ggs)

The chains appear well mixed and very similar

  • gss_autocorrelation (autocorrelation function): plots the autocorrelation between successive MCMC sample lags for each parameter and each chain
ggs_autocorrelation(day.ggs)

There is no evidence of auto-correlation in the MCMC samples

  • stan_rhat: Rhat is a scale reduction factor measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
ggs_Rhat(day.ggs)

All Rhat values are below 1.05, suggesting the chains have converged.

  • stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

ggs_effective(day.ggs)
Warning: Returning more (or less) than 1 row per `summarise()` group was deprecated in
dplyr 1.1.0.
ℹ Please use `reframe()` instead.
ℹ When switching from `summarise()` to `reframe()`, remember that `reframe()`
  always returns an ungrouped data frame and adjust accordingly.
ℹ The deprecated feature was likely used in the ggmcmc package.
  Please report the issue at <https://github.com/xfim/ggmcmc/issues/>.

Ratios all very high.

More diagnostics
ggs_crosscorrelation(day.ggs)

ggs_grb(day.ggs)

6.0.1 stan plots

The brms package offers a range of MCMC diagnostics. Lets start with the MCMC diagnostics.

Of these, we will focus on:

  • stan_trace: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different colour, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
day.brm3$fit |> stan_trace()

day.brm3$fit |> stan_trace(inc_warmup=TRUE)

The chains appear well mixed and very similar

  • stan_acf (auto-correlation function): plots the auto-correlation between successive MCMC sample lags for each parameter and each chain
day.brm3$fit |> stan_ac() 

There is no evidence of auto-correlation in the MCMC samples

  • stan_rhat: Rhat is a scale reduction factor measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
day.brm3$fit |> stan_rhat() 
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

All Rhat values are below 1.05, suggesting the chains have converged.

  • stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

day.brm3$fit |> stan_ess()
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Ratios all very high.

day.brm3$fit |> stan_dens(separate_chains = TRUE)

7 Model validation

Post predictive checks provide additional diagnostics about the fit of the model. Specifically, they provide a comparison between predictions drawn from the model and the observed data used to train the model.

See list of available diagnostics by name
available_ppc()
bayesplot PPC module:
  ppc_bars
  ppc_bars_grouped
  ppc_boxplot
  ppc_dens
  ppc_dens_overlay
  ppc_dens_overlay_grouped
  ppc_ecdf_overlay
  ppc_ecdf_overlay_grouped
  ppc_error_binned
  ppc_error_hist
  ppc_error_hist_grouped
  ppc_error_scatter
  ppc_error_scatter_avg
  ppc_error_scatter_avg_grouped
  ppc_error_scatter_avg_vs_x
  ppc_freqpoly
  ppc_freqpoly_grouped
  ppc_hist
  ppc_intervals
  ppc_intervals_grouped
  ppc_km_overlay
  ppc_km_overlay_grouped
  ppc_loo_intervals
  ppc_loo_pit
  ppc_loo_pit_overlay
  ppc_loo_pit_qq
  ppc_loo_ribbon
  ppc_pit_ecdf
  ppc_pit_ecdf_grouped
  ppc_ribbon
  ppc_ribbon_grouped
  ppc_rootogram
  ppc_scatter
  ppc_scatter_avg
  ppc_scatter_avg_grouped
  ppc_stat
  ppc_stat_2d
  ppc_stat_freqpoly
  ppc_stat_freqpoly_grouped
  ppc_stat_grouped
  ppc_violin_grouped
  • dens_overlay: plots the density distribution of the observed data (black line) overlayed on top of 50 density distributions generated from draws from the model (light blue). Ideally, the 50 realisations should be roughly consistent with the observed data.
pp_check(day.rstanarm3,  plotfun='dens_overlay')

The model draws appear deviate from the observed data.

  • error_scatter_avg: this plots the observed values against the average residuals. Similar to a residual plot, we do not want to see any patterns in this plot. There is some pattern remaining in these residuals.
pp_check(day.rstanarm3, plotfun='error_scatter_avg')

The predictive error seems to be related to the predictor - the model performs poorest at higher mussel clump areas.

  • error_scatter_avg_vs_x: this is similar to a regular residual plot and as such should be interpreted as such. Again, this is not interpretable for binary data.
pp_check(day.rstanarm3, x=as.numeric(day$TREAT), plotfun='error_scatter_avg_vs_x')

  • intervals: plots the observed data overlayed on top of posterior predictions associated with each level of the predictor. Ideally, the observed data should all fall within the predictive intervals.
pp_check(day.rstanarm3, x=as.numeric(day$TREAT), plotfun='intervals')

The modelled predictions seem to underestimate the uncertainty with increasing mussel clump area.

The shinystan package allows the full suite of MCMC diagnostics and posterior predictive checks to be accessed via a web interface.

#library(shinystan)
#launch_shinystan(day.rstanarm3)

DHARMa residuals provide very useful diagnostics. Unfortunately, we cannot directly use the simulateResiduals() function to generate the simulated residuals. However, if we are willing to calculate some of the components yourself, we can still obtain the simulated residuals from the fitted stan model.

We need to supply:

  • simulated (predicted) responses associated with each observation.
  • observed values
  • fitted (predicted) responses (averaged) associated with each observation
preds <- posterior_predict(day.rstanarm3,  ndraws=250,  summary=FALSE)
day.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = day$BARNACLE,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse = TRUE)
plot(day.resids)

Conclusions:

  • the simulated residuals DOES NOT suggest any issues with the fitted model

Post predictive checks provide additional diagnostics about the fit of the model. Specifically, they provide a comparison between predictions drawn from the model and the observed data used to train the model.

See list of available diagnostics by name
available_ppc()
bayesplot PPC module:
  ppc_bars
  ppc_bars_grouped
  ppc_boxplot
  ppc_dens
  ppc_dens_overlay
  ppc_dens_overlay_grouped
  ppc_ecdf_overlay
  ppc_ecdf_overlay_grouped
  ppc_error_binned
  ppc_error_hist
  ppc_error_hist_grouped
  ppc_error_scatter
  ppc_error_scatter_avg
  ppc_error_scatter_avg_grouped
  ppc_error_scatter_avg_vs_x
  ppc_freqpoly
  ppc_freqpoly_grouped
  ppc_hist
  ppc_intervals
  ppc_intervals_grouped
  ppc_km_overlay
  ppc_km_overlay_grouped
  ppc_loo_intervals
  ppc_loo_pit
  ppc_loo_pit_overlay
  ppc_loo_pit_qq
  ppc_loo_ribbon
  ppc_pit_ecdf
  ppc_pit_ecdf_grouped
  ppc_ribbon
  ppc_ribbon_grouped
  ppc_rootogram
  ppc_scatter
  ppc_scatter_avg
  ppc_scatter_avg_grouped
  ppc_stat
  ppc_stat_2d
  ppc_stat_freqpoly
  ppc_stat_freqpoly_grouped
  ppc_stat_grouped
  ppc_violin_grouped
  • dens_overlay: plots the density distribution of the observed data (black line) overlayed on top of 50 density distributions generated from draws from the model (light blue). Ideally, the 50 realisations should be roughly consistent with the observed data.
day.brm3 |> pp_check(type = 'dens_overlay', ndraws=200)

The model draws appear deviate from the observed data.

  • error_scatter_avg: this plots the observed values against the average residuals. Similar to a residual plot, we do not want to see any patterns in this plot. There is some pattern remaining in these residuals.
day.brm3 |> pp_check(type = 'error_scatter_avg')
Using all posterior draws for ppc type 'error_scatter_avg' by default.

The predictive error seems to be related to the predictor - the model performs poorest at higher mussel clump areas.

  • intervals: plots the observed data overlayed on top of posterior predictions associated with each level of the predictor. Ideally, the observed data should all fall within the predictive intervals.
day.brm3 |> pp_check(group='TREAT', type='intervals')
Using all posterior draws for ppc type 'intervals' by default.
Warning: The following arguments were unrecognized and ignored: group

The modelled predictions seem to underestimate the uncertainty with increasing mussel clump area.

The shinystan package allows the full suite of MCMC diagnostics and posterior predictive checks to be accessed via a web interface.

#library(shinystan)
#launch_shinystan(day.brm3)

DHARMa residuals provide very useful diagnostics. Unfortunately, we cannot directly use the simulateResiduals() function to generate the simulated residuals. However, if we are willing to calculate some of the components yourself, we can still obtain the simulated residuals from the fitted stan model.

We need to supply:

  • simulated (predicted) responses associated with each observation.
  • observed values
  • fitted (predicted) responses (averaged) associated with each observation
preds <- day.brm3 |> posterior_predict(ndraws = 250,  summary = FALSE)
day.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = day$BARNACLE,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse = TRUE)
day.resids |> plot()

day.resids <- make_brms_dharma_res(day.brm3, integerResponse = TRUE)
wrap_elements(~testUniformity(day.resids)) +
               wrap_elements(~plotResiduals(day.resids, form = factor(rep(1, nrow(day))))) +
               wrap_elements(~plotResiduals(day.resids, quantreg = TRUE)) +
               wrap_elements(~testDispersion(day.resids))

Conclusions:

  • the simulated residuals DO NOT suggest any issues with the model fit

8 Partial effects plots

day.rstanarm3 |> ggpredict() |> plot(add.data=TRUE)
$TREAT

day.rstanarm3 |> ggemmeans(~TREAT,  type='fixed') |> plot(add.data=TRUE)

day.rstanarm3 |>
    epred_draws(newdata=day) |>
  median_hdci() |>
  ggplot(aes(x=TREAT, y=.epred)) +
  geom_pointrange(aes(ymin=.lower, ymax=.upper)) + 
  geom_line() +
  geom_point(data=day,  aes(y=BARNACLE,  x=TREAT))

day.brm3 |> conditional_effects() |> plot(points = TRUE)

day.brm3 |> ggpredict() |> plot(add.data = TRUE)
$TREAT

day.brm3 |> ggemmeans(~TREAT) |> plot(add.data = TRUE)

day.brm3 |>
    epred_draws(newdata = day) |>
    median_hdci() |>
    ggplot(aes(x = TREAT, y = .epred)) +
    geom_pointrange(aes(ymin = .lower, ymax = .upper)) + 
    geom_line() +
    geom_point(data = day,  aes(y = BARNACLE,  x = TREAT))

9 Model investigation

The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).

summary(day.rstanarm3)

Model Info:
 function:     stan_glm
 family:       poisson [log]
 formula:      BARNACLE ~ TREAT
 algorithm:    sampling
 sample:       2400 (posterior sample size)
 priors:       see help('prior_summary')
 observations: 20
 predictors:   4

Estimates:
              mean   sd   10%   50%   90%
(Intercept)  3.1    0.1  3.0   3.1   3.2 
TREATALG2    0.2    0.1  0.1   0.2   0.4 
TREATNB     -0.4    0.2 -0.6  -0.4  -0.2 
TREATS      -0.5    0.2 -0.7  -0.5  -0.3 

Fit Diagnostics:
           mean   sd   10%   50%   90%
mean_PPD 19.7    1.4 17.9  19.7  21.5 

The mean_ppd is the sample average posterior predictive distribution of the outcome variable (for details see help('summary.stanreg')).

MCMC diagnostics
              mcse Rhat n_eff
(Intercept)   0.0  1.0  2406 
TREATALG2     0.0  1.0  2378 
TREATNB       0.0  1.0  2314 
TREATS        0.0  1.0  2346 
mean_PPD      0.0  1.0  2410 
log-posterior 0.0  1.0  2291 

For each parameter, mcse is Monte Carlo standard error, n_eff is a crude measure of effective sample size, and Rhat is the potential scale reduction factor on split chains (at convergence Rhat=1).

Conclusions:

  • in the Model Info, we are informed that the total MCMC posterior sample size is 2400 and that there were 20 raw observations.
  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is 3.1. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 22.13.
  • the estimated effect of ALG2 vs ALG1 is 0.24 (mean) or 0.08 (median) with a standard deviation of 0. The 90% credibility intervals indicate that we are 90% confident that the slope is between 0.24 and 0.25 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 1.27 times higher than that on ALG1. This represents a 27% increase in barnacle recruitment.
  • the estimated effect of NB and S are -0.39 and -0.52 respectively, which equate to 1.48 and 1.68 fold declines respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
tidyMCMC(day.rstanarm3$stanfit, estimate.method='median',  conf.int=TRUE,  conf.method='HPDinterval',  rhat=TRUE, ess=TRUE)
# A tibble: 6 × 7
  term          estimate std.error   conf.low conf.high  rhat   ess
  <chr>            <dbl>     <dbl>      <dbl>     <dbl> <dbl> <int>
1 (Intercept)      3.10     0.0920   2.92        3.28   1.00   2406
2 TREATALG2        0.246    0.122   -0.000988    0.478  1.00   2378
3 TREATNB         -0.388    0.151   -0.693      -0.0961 0.999  2314
4 TREATS          -0.520    0.153   -0.787      -0.192  1.00   2346
5 mean_PPD        19.7      1.40    16.8        22.4    1.00   2410
6 log-posterior  -61.8      1.35   -64.8       -60.2    1.00   2291

Conclusions:

  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is 3.1. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 22.12.
  • the estimated effect of ALG2 vs ALG1 is 0.25 (median) with a standard error of 0.12. The 95% credibility intervals indicate that we are 95% confident that the effect is between 0 and 0.48 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 1.28 times higher than that on ALG1. This represents a 28% increase in barnacle recruitment.
  • the estimated effect of NB and S are -0.39 and -0.52 respectively, which equate to 1.47 and 1.68 fold declines respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
day.rstanarm3$stanfit |>
    summarise_draws(median,
                    HDInterval::hdi,
                    rhat, length, ess_bulk, ess_tail)
# A tibble: 6 × 8
  variable       median      lower    upper  rhat length ess_bulk ess_tail
  <chr>           <num>      <num>    <num> <num>  <num>    <num>    <num>
1 (Intercept)     3.10    2.92       3.28   1.00    2400    2407.    2453.
2 TREATALG2       0.246  -0.000988   0.478  1.00    2400    2379.    2207.
3 TREATNB        -0.388  -0.693     -0.0961 0.999   2400    2333.    2274.
4 TREATS         -0.520  -0.787     -0.192  1.00    2400    2355.    2542.
5 mean_PPD       19.7    16.8       22.4    1.00    2400    2415.    2230.
6 log-posterior -61.8   -64.8      -60.2    1.00    2400    2329.    2211.

We can also alter the CI level.

day.rstanarm3$stanfit |>
    summarise_draws(median,
                    ~HDInterval::hdi(.x, credMass = 0.9),
                    rhat, length, ess_bulk, ess_tail)
# A tibble: 6 × 8
  variable       median    lower   upper  rhat length ess_bulk ess_tail
  <chr>           <num>    <num>   <num> <num>  <num>    <num>    <num>
1 (Intercept)     3.10    2.94     3.24  1.00    2400    2407.    2453.
2 TREATALG2       0.246   0.0313   0.429 1.00    2400    2379.    2207.
3 TREATNB        -0.388  -0.634   -0.141 0.999   2400    2333.    2274.
4 TREATS         -0.520  -0.766   -0.269 1.00    2400    2355.    2542.
5 mean_PPD       19.7    17.4     22     1.00    2400    2415.    2230.
6 log-posterior -61.8   -63.9    -60.2   1.00    2400    2329.    2211.

Arguably, it would be better to back-transform to the ratio scale

day.rstanarm3$stanfit |>
    summarise_draws(
        ~ median(exp(.x)),
        ~HDInterval::hdi(exp(.x)),
        rhat, length, ess_bulk, ess_tail)
# A tibble: 6 × 8
  variable   `~median(exp(.x))`    lower    upper  rhat length ess_bulk ess_tail
  <chr>                   <num>    <num>    <num> <num>  <num>    <num>    <num>
1 (Intercep…           2.21e+ 1 1.84e+ 1 2.62e+ 1 1.00    2400    2407.    2453.
2 TREATALG2            1.28e+ 0 9.74e- 1 1.58e+ 0 1.00    2400    2379.    2207.
3 TREATNB              6.79e- 1 4.72e- 1 8.71e- 1 0.999   2400    2333.    2274.
4 TREATS               5.94e- 1 4.30e- 1 7.89e- 1 1.00    2400    2355.    2542.
5 mean_PPD             3.59e+ 8 5.96e+ 6 3.58e+ 9 1.00    2400    2415.    2230.
6 log-poste…           1.45e-27 3.56e-31 5.55e-27 1.00    2400    2329.    2211.
day.rstanarm3$stanfit |> as_draws_df()
# A draws_df: 800 iterations, 3 chains, and 6 variables
   (Intercept) TREATALG2 TREATNB TREATS mean_PPD log-posterior
1          3.1     0.184   -0.38  -0.62       19           -60
2          3.0     0.260   -0.35  -0.33       18           -61
3          3.0     0.410   -0.36  -0.36       23           -61
4          3.2     0.236   -0.39  -0.53       22           -62
5          3.2     0.213   -0.47  -0.60       20           -61
6          3.1     0.405   -0.34  -0.58       20           -62
7          3.2     0.116   -0.55  -0.70       18           -62
8          3.3     0.021   -0.48  -0.67       20           -62
9          3.0     0.323   -0.21  -0.43       19           -61
10         3.2     0.109   -0.49  -0.37       23           -64
# ... with 2390 more draws
# ... hidden reserved variables {'.chain', '.iteration', '.draw'}
day.rstanarm3$stanfit |>
  as_draws_df() |>
  summarise_draws(
    median,
    ~ HDInterval::hdi(.x),
    rhat,
    length,
    ess_bulk, ess_tail
  )
# A tibble: 6 × 8
  variable       median      lower    upper  rhat length ess_bulk ess_tail
  <chr>           <num>      <num>    <num> <num>  <num>    <num>    <num>
1 (Intercept)     3.10    2.92       3.28   1.00    2400    2407.    2453.
2 TREATALG2       0.246  -0.000988   0.478  1.00    2400    2379.    2207.
3 TREATNB        -0.388  -0.693     -0.0961 0.999   2400    2333.    2274.
4 TREATS         -0.520  -0.787     -0.192  1.00    2400    2355.    2542.
5 mean_PPD       19.7    16.8       22.4    1.00    2400    2415.    2230.
6 log-posterior -61.8   -64.8      -60.2    1.00    2400    2329.    2211.
day.rstanarm3$stanfit |>
    as_draws_df() |>
    exp() |>
    summarise_draws(
        median,
        ~ HDInterval::hdi(.x),
        rhat,
        length,
        ess_bulk, ess_tail
    )
# A tibble: 6 × 8
  variable        median    lower    upper  rhat length ess_bulk ess_tail
  <chr>            <num>    <num>    <num> <num>  <num>    <num>    <num>
1 (Intercept)   2.21e+ 1 1.84e+ 1 2.62e+ 1 1.00    2400    2407.    2453.
2 TREATALG2     1.28e+ 0 9.74e- 1 1.58e+ 0 1.00    2400    2379.    2207.
3 TREATNB       6.79e- 1 4.72e- 1 8.71e- 1 0.999   2400    2333.    2274.
4 TREATS        5.94e- 1 4.30e- 1 7.89e- 1 1.00    2400    2355.    2542.
5 mean_PPD      3.59e+ 8 5.96e+ 6 3.58e+ 9 1.00    2400    2415.    2230.
6 log-posterior 1.45e-27 3.56e-31 5.55e-27 1.00    2400    2329.    2211.

Due to the presence of a log transform in the predictor, it is better to use the regex version.

day.rstanarm3 |> get_variables()
 [1] "(Intercept)"   "TREATALG2"     "TREATNB"       "TREATS"       
 [5] "accept_stat__" "stepsize__"    "treedepth__"   "n_leapfrog__" 
 [9] "divergent__"   "energy__"     
day.draw <- day.rstanarm3 |> gather_draws(`.Intercept.*|.*TREAT.*`,  regex=TRUE)
day.draw
# A tibble: 9,600 × 5
# Groups:   .variable [4]
   .chain .iteration .draw .variable   .value
    <int>      <int> <int> <chr>        <dbl>
 1      1          1     1 (Intercept)   3.13
 2      1          2     2 (Intercept)   3.00
 3      1          3     3 (Intercept)   3.04
 4      1          4     4 (Intercept)   3.20
 5      1          5     5 (Intercept)   3.19
 6      1          6     6 (Intercept)   3.06
 7      1          7     7 (Intercept)   3.16
 8      1          8     8 (Intercept)   3.26
 9      1          9     9 (Intercept)   3.03
10      1         10    10 (Intercept)   3.23
# ℹ 9,590 more rows
exceedP <- function(x, Val = 0) mean(x>Val)

day.rstanarm3 |>
    gather_draws(`.Intercept.*|.*TREAT.*`,  regex=TRUE) |>
    mutate(.value = exp(.value)) |>
    summarise_draws(median,
                    HDInterval::hdi,
                    rhat,
                    length,
                    ess_bulk,
                    ess_tail,
                    ~ exceedP(.x, 1))
# A tibble: 4 × 10
# Groups:   .variable [4]
  .variable   variable median  lower  upper  rhat length ess_bulk ess_tail
  <chr>       <chr>     <dbl>  <dbl>  <dbl> <dbl>  <dbl>    <dbl>    <dbl>
1 (Intercept) .value   22.1   18.4   26.2   1.00    2400    2407.    2453.
2 TREATALG2   .value    1.28   0.974  1.58  1.00    2400    2379.    2207.
3 TREATNB     .value    0.679  0.472  0.871 0.999   2400    2333.    2274.
4 TREATS      .value    0.594  0.430  0.789 1.00    2400    2355.    2542.
# ℹ 1 more variable: `~exceedP(.x, 1)` <dbl>

We can then summarise this

day.draw |> median_hdci(.value)
# A tibble: 4 × 7
  .variable   .value    .lower  .upper .width .point .interval
  <chr>        <dbl>     <dbl>   <dbl>  <dbl> <chr>  <chr>    
1 (Intercept)  3.10   2.92      3.28     0.95 median hdci     
2 TREATALG2    0.246 -0.000988  0.478    0.95 median hdci     
3 TREATNB     -0.388 -0.693    -0.0961   0.95 median hdci     
4 TREATS      -0.520 -0.787    -0.192    0.95 median hdci     

We could alternatively express the parameters on the response scale.

day.draw |> median_hdci(exp(.value))
# A tibble: 4 × 7
  .variable   `exp(.value)` .lower .upper .width .point .interval
  <chr>               <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 (Intercept)        22.1   18.4   26.2     0.95 median hdci     
2 TREATALG2           1.28   0.974  1.58    0.95 median hdci     
3 TREATNB             0.679  0.472  0.871   0.95 median hdci     
4 TREATS              0.594  0.430  0.789   0.95 median hdci     

Conclusions:

  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is 3.1. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 22.12.
  • the estimated effect of ALG2 vs ALG1 is 0.25 (median) with a standard error of 0. The 95% credibility intervals indicate that we are 95% confident that the effect is between 0.48 and 0.95 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 1.28 times higher than that on ALG1. This represents a 28% increase in barnacle recruitment.
  • the estimated effect of NB and S are -0.39 and -0.52 respectively, which equate to 1.47 and 1.68 fold declines respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
day.rstanarm3 |> plot(plotfun='mcmc_intervals') 

day.rstanarm3 |> 
  gather_draws(`.Intercept.*|.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
  stat_halfeye(aes(x=.value,  y=.variable)) +
  facet_wrap(~.variable, scales='free')

day.rstanarm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    stat_halfeye(aes(x=.value,  y=.variable)) +
    geom_vline(xintercept = 0, linetype = 'dashed')

day.rstanarm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    stat_halfeye(aes(x=exp(.value),  y=.variable)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans())

day.rstanarm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges(aes(x=.value, y = .variable), alpha=0.4) +
    geom_vline(xintercept = 0, linetype = 'dashed')
Picking joint bandwidth of 0.027

##Or on a fractional scale
day.rstanarm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges_gradient(aes(x=exp(.value),
                                     y = .variable,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_c(option = "C")
Warning: `stat(x)` was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(x)` instead.
Picking joint bandwidth of 0.0389
Warning: Using the `size` aesthetic with geom_segment was deprecated in ggplot2 3.4.0.
ℹ Please use the `linewidth` aesthetic instead.

This is purely a graphical depiction on the posteriors.

day.rstanarm3 |> tidy_draws()
# A tibble: 2,400 × 13
   .chain .iteration .draw `(Intercept)` TREATALG2 TREATNB TREATS accept_stat__
    <int>      <int> <int>         <dbl>     <dbl>   <dbl>  <dbl>         <dbl>
 1      1          1     1          3.13    0.184   -0.379 -0.625         0.992
 2      1          2     2          3.00    0.260   -0.345 -0.329         0.843
 3      1          3     3          3.04    0.410   -0.356 -0.361         0.990
 4      1          4     4          3.20    0.236   -0.393 -0.525         0.996
 5      1          5     5          3.19    0.213   -0.472 -0.598         0.993
 6      1          6     6          3.06    0.405   -0.338 -0.580         0.962
 7      1          7     7          3.16    0.116   -0.550 -0.697         0.966
 8      1          8     8          3.26    0.0213  -0.481 -0.666         0.972
 9      1          9     9          3.03    0.323   -0.212 -0.431         0.975
10      1         10    10          3.23    0.109   -0.486 -0.367         0.985
# ℹ 2,390 more rows
# ℹ 5 more variables: stepsize__ <dbl>, treedepth__ <dbl>, n_leapfrog__ <dbl>,
#   divergent__ <dbl>, energy__ <dbl>
day.rstanarm3 |> spread_draws(`.Intercept.*|.*TREAT.*`,  regex=TRUE)
# A tibble: 2,400 × 7
   .chain .iteration .draw `(Intercept)` TREATALG2 TREATNB TREATS
    <int>      <int> <int>         <dbl>     <dbl>   <dbl>  <dbl>
 1      1          1     1          3.13    0.184   -0.379 -0.625
 2      1          2     2          3.00    0.260   -0.345 -0.329
 3      1          3     3          3.04    0.410   -0.356 -0.361
 4      1          4     4          3.20    0.236   -0.393 -0.525
 5      1          5     5          3.19    0.213   -0.472 -0.598
 6      1          6     6          3.06    0.405   -0.338 -0.580
 7      1          7     7          3.16    0.116   -0.550 -0.697
 8      1          8     8          3.26    0.0213  -0.481 -0.666
 9      1          9     9          3.03    0.323   -0.212 -0.431
10      1         10    10          3.23    0.109   -0.486 -0.367
# ℹ 2,390 more rows
day.rstanarm3 |> posterior_samples() |> as_tibble()
Warning: Method 'posterior_samples' is deprecated. Please see ?as_draws for
recommended alternatives.
# A tibble: 2,400 × 4
   `(Intercept)` TREATALG2 TREATNB TREATS
           <dbl>     <dbl>   <dbl>  <dbl>
 1          3.13    0.184   -0.379 -0.625
 2          3.00    0.260   -0.345 -0.329
 3          3.04    0.410   -0.356 -0.361
 4          3.20    0.236   -0.393 -0.525
 5          3.19    0.213   -0.472 -0.598
 6          3.06    0.405   -0.338 -0.580
 7          3.16    0.116   -0.550 -0.697
 8          3.26    0.0213  -0.481 -0.666
 9          3.03    0.323   -0.212 -0.431
10          3.23    0.109   -0.486 -0.367
# ℹ 2,390 more rows

Unfortunately, \(R^2\) calculations for models other than Gaussian and Binomial have not yet been implemented for rstanarm models yet.

#day.rstanarm3 |> bayes_R2() |> median_hdci

The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).

day.brm3 |> summary()
 Family: poisson 
  Links: mu = log 
Formula: BARNACLE ~ TREAT 
   Data: day (Number of observations: 20) 
  Draws: 3 chains, each with iter = 5000; warmup = 1000; thin = 5;
         total post-warmup draws = 2400

Population-Level Effects: 
          Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
Intercept     3.11      0.09     2.92     3.28 1.00     2160     2453
TREATALG2     0.24      0.13    -0.01     0.49 1.00     2227     2354
TREATNB      -0.40      0.15    -0.70    -0.12 1.00     2540     2303
TREATS       -0.53      0.15    -0.85    -0.24 1.00     2410     2368

Draws were sampled using sample(hmc). For each parameter, Bulk_ESS
and Tail_ESS are effective sample size measures, and Rhat is the potential
scale reduction factor on split chains (at convergence, Rhat = 1).

Conclusions:

  • in the Model Info, we are informed that the total MCMC posterior sample size is 2400 and that there were 20 raw observations.
  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is 3.11. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 22.33.
  • the estimated effect of ALG2 vs ALG1 is 0.24 (mean) or 0.49 (median) with a standard deviation of 0.13. The 90% credibility intervals indicate that we are 90% confident that the slope is between 0.24 and 1 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 1.27 times higher than that on ALG1. This represents a 27% increase in barnacle recruitment.
  • the estimated effect of NB and S are -0.4 and -0.53 respectively, which equate to 1.5 and 1.7 fold decline respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
day.brm3$fit |> tidyMCMC(estimate.method = 'median',
                          conf.int = TRUE,
                          conf.method = 'HPDinterval',
                          rhat = TRUE,
                          ess = TRUE)
# A tibble: 7 × 7
  term            estimate std.error conf.low conf.high  rhat   ess
  <chr>              <dbl>     <dbl>    <dbl>     <dbl> <dbl> <int>
1 b_Intercept        3.11     0.0927   2.92       3.28  1.00   2174
2 b_TREATALG2        0.241    0.126   -0.0204     0.475 1.00   2240
3 b_TREATNB         -0.404    0.146   -0.716     -0.145 1.00   2508
4 b_TREATS          -0.528    0.154   -0.848     -0.239 1.00   2404
5 prior_Intercept    3.23     2.21    -1.43       7.23  0.999  2330
6 prior_b            0.122    2.42    -4.83       4.50  0.999  2473
7 lprior            -7.14     0.0197  -7.18      -7.11  1.00   2446

Conclusions:

  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is 3.11. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 22.38.
  • the estimated effect of ALG2 vs ALG1 is 0.24 (median) with a standard error of 0.13. The 95% credibility intervals indicate that we are 95% confident that the effect is between -0.02 and 0.48 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 1.27 times higher than that on ALG1. This represents a 27% increase in barnacle recruitment.
  • the estimated effect of NB and S are -0.4 and -0.53 respectively, which equate to 1.5 and 1.7 fold declines respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
day.brm3 |> as_draws_df()
# A draws_df: 800 iterations, 3 chains, and 8 variables
   b_Intercept b_TREATALG2 b_TREATNB b_TREATS prior_Intercept prior_b lprior
1          3.1       0.255     -0.61    -0.63           -0.23   -1.33   -7.2
2          3.0       0.373     -0.15    -0.46            5.45   -1.21   -7.1
3          3.1       0.284     -0.45    -0.59            5.42   -3.34   -7.1
4          2.9       0.420     -0.10    -0.39            2.03    2.10   -7.1
5          3.0       0.239     -0.22    -0.48            2.00    0.54   -7.1
6          2.9       0.429     -0.23    -0.46            4.59   -3.19   -7.1
7          3.1       0.214     -0.35    -0.47            4.75    0.92   -7.1
8          3.1       0.307     -0.40    -0.45           -1.08    2.02   -7.1
9          3.2      -0.096     -0.61    -0.85            3.66    2.59   -7.2
10         3.1       0.219     -0.39    -0.50            5.11    4.63   -7.1
   lp__
1   -65
2   -65
3   -64
4   -65
5   -65
6   -65
7   -64
8   -65
9   -68
10  -63
# ... with 2390 more draws
# ... hidden reserved variables {'.chain', '.iteration', '.draw'}
day.brm3 |>
  as_draws_df() |>
  summarise_draws(
    median,
    HDInterval::hdi,
    rhat,
    length,
    ess_bulk, ess_tail
  )
# A tibble: 8 × 8
  variable         median    lower   upper  rhat length ess_bulk ess_tail
  <chr>             <num>    <num>   <num> <num>  <num>    <num>    <num>
1 b_Intercept       3.11    2.92     3.28   1.00   2400    2160.    2453.
2 b_TREATALG2       0.241  -0.0204   0.475  1.00   2400    2227.    2354.
3 b_TREATNB        -0.404  -0.716   -0.145  1.00   2400    2540.    2303.
4 b_TREATS         -0.528  -0.848   -0.239  1.00   2400    2410.    2368.
5 prior_Intercept   3.23   -1.43     7.23   1.00   2400    2336.    2252.
6 prior_b           0.122  -4.83     4.50   1.00   2400    2481.    2328.
7 lprior           -7.14   -7.18    -7.11   1.00   2400    2455.    2382.
8 lp__            -65.0   -68.0    -63.4    1.00   2400    2474.    2175.
day.brm3 |>
  as_draws_df() |>
    exp() |>
  summarise_draws(
    median,
    HDInterval::hdi,
    rhat,
    length,
    ess_bulk, ess_tail
  )
# A tibble: 8 × 8
  variable          median    lower    upper  rhat length ess_bulk ess_tail
  <chr>              <num>    <num>    <num> <num>  <num>    <num>    <num>
1 b_Intercept     2.24e+ 1 1.84e+ 1 2.64e+ 1  1.00   2400    2160.    2453.
2 b_TREATALG2     1.27e+ 0 9.71e- 1 1.60e+ 0  1.00   2400    2227.    2354.
3 b_TREATNB       6.68e- 1 4.89e- 1 8.65e- 1  1.00   2400    2540.    2303.
4 b_TREATS        5.90e- 1 4.16e- 1 7.74e- 1  1.00   2400    2410.    2368.
5 prior_Intercept 2.52e+ 1 7.52e- 3 8.57e+ 2  1.00   2400    2336.    2252.
6 prior_b         1.13e+ 0 3.23e- 4 6.16e+ 1  1.00   2400    2481.    2328.
7 lprior          7.92e- 4 7.61e- 4 8.19e- 4  1.00   2400    2455.    2382.
8 lp__            6.03e-29 3.11e-33 2.27e-28  1.00   2400    2474.    2175.

Due to the presence of a log transform in the predictor, it is better to use the regex version.

day.brm3 |> get_variables()
 [1] "b_Intercept"     "b_TREATALG2"     "b_TREATNB"       "b_TREATS"       
 [5] "prior_Intercept" "prior_b"         "lprior"          "lp__"           
 [9] "accept_stat__"   "treedepth__"     "stepsize__"      "divergent__"    
[13] "n_leapfrog__"    "energy__"       
day.draw <- day.brm3 |>
    gather_draws(`.Intercept.*|.*TREAT.*`,  regex = TRUE)
day.draw
# A tibble: 7,200 × 5
# Groups:   .variable [3]
   .chain .iteration .draw .variable    .value
    <int>      <int> <int> <chr>         <dbl>
 1      1          1     1 b_TREATALG2  0.255 
 2      1          2     2 b_TREATALG2  0.373 
 3      1          3     3 b_TREATALG2  0.284 
 4      1          4     4 b_TREATALG2  0.420 
 5      1          5     5 b_TREATALG2  0.239 
 6      1          6     6 b_TREATALG2  0.429 
 7      1          7     7 b_TREATALG2  0.214 
 8      1          8     8 b_TREATALG2  0.307 
 9      1          9     9 b_TREATALG2 -0.0957
10      1         10    10 b_TREATALG2  0.219 
# ℹ 7,190 more rows
day.brm3 |>
    gather_draws(`.Intercept.*|.*TREAT.*`,  regex = TRUE) |>
    mutate(.value = exp(.value)) |>
    summarise_draws(median,
                    ~HDInterval::hdi(.x, credMass = 0.95),
                    rhat,
                    length,
                    ess_bulk, ess_tail)
# A tibble: 3 × 9
# Groups:   .variable [3]
  .variable   variable median lower upper  rhat length ess_bulk ess_tail
  <chr>       <chr>     <dbl> <dbl> <dbl> <dbl>  <dbl>    <dbl>    <dbl>
1 b_TREATALG2 .value    1.27  0.971 1.60   1.00   2400    2227.    2354.
2 b_TREATNB   .value    0.668 0.489 0.865  1.00   2400    2540.    2303.
3 b_TREATS    .value    0.590 0.416 0.774  1.00   2400    2410.    2368.
exceedP <- function(x, Val = 0) mean(x>Val)
day.brm3 |>
    tidy_draws() |>
    exp() |>
    dplyr::select(starts_with("b_")) |>
    summarise_draws(median,
                    ~HDInterval::hdi(.x, credMass = 0.9),
                    rhat,
                    ess_bulk, ess_tail,
                    ~exceedP(.x, 1))
# A tibble: 4 × 8
  variable    median  lower  upper  rhat ess_bulk ess_tail `~exceedP(.x, 1)`
  <chr>        <num>  <num>  <num> <num>    <num>    <num>             <num>
1 b_Intercept 22.4   19.0   25.7    1.00    2152.    2446.           1      
2 b_TREATALG2  1.27   1.03   1.54   1.00    2236.    2341.           0.972  
3 b_TREATNB    0.668  0.520  0.844  1.00    2527.    2289.           0.00167
4 b_TREATS     0.590  0.445  0.744  1.00    2401.    2362.           0      

We can then summarise this

day.draw |> median_hdci(.value)
# A tibble: 3 × 7
  .variable   .value  .lower .upper .width .point .interval
  <chr>        <dbl>   <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 b_TREATALG2  0.241 -0.0204  0.475   0.95 median hdci     
2 b_TREATNB   -0.404 -0.716  -0.145   0.95 median hdci     
3 b_TREATS    -0.528 -0.848  -0.239   0.95 median hdci     

We could alternatively express the parameters on the response scale.

day.draw |> 
  median_hdci(exp(.value))
# A tibble: 3 × 7
  .variable   `exp(.value)` .lower .upper .width .point .interval
  <chr>               <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 b_TREATALG2         1.27   0.971  1.60    0.95 median hdci     
2 b_TREATNB           0.668  0.489  0.865   0.95 median hdci     
3 b_TREATS            0.590  0.416  0.774   0.95 median hdci     
day.brm3 |> 
  gather_draws(`.Intercept.*|.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
  stat_halfeye(aes(x=.value,  y=.variable)) +
  facet_wrap(~.variable, scales='free')

Conclusions:

  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is 0.24. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 1.27.
  • the estimated effect of ALG2 vs ALG1 is -0.4 (median) with a standard error of -0.72. The 95% credibility intervals indicate that we are 95% confident that the effect is between -0.14 and 0.95 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 0.67 times higher than that on ALG1. This represents a -33% increase in barnacle recruitment.
  • the estimated effect of NB and S are -0.53 and NA respectively, which equate to 1.7 and NA fold declines respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
day.brm3$fit |> plot(type='intervals') 
ci_level: 0.8 (80% intervals)
outer_level: 0.95 (95% intervals)

## Link scale
day.brm3 |>
    gather_draws(`.Intercept.*|.*TREAT.*`, regex=TRUE) |> 
    ggplot() +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    geom_vline(xintercept=0, linetype='dashed') +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) 

## Fractional scale
day.brm3 |>
    gather_draws(`.Intercept.*|.*TREAT.*`, regex=TRUE) |>
    mutate(.value=exp(.value)) |>
    ggplot() +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    geom_vline(xintercept=1, linetype='dashed') +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) +
    scale_x_continuous(trans = scales::log2_trans())

day.brm3 |> 
  gather_draws(`.Intercept.*|.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
  stat_halfeye(aes(x=.value,  y=.variable)) +
  facet_wrap(~.variable, scales='free')

day.brm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    stat_halfeye(aes(x=.value,  y=.variable)) +
    geom_vline(xintercept = 0, linetype = 'dashed')

day.brm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    stat_halfeye(aes(x=exp(.value),  y=.variable)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans())

day.brm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges(aes(x=.value, y = .variable), alpha=0.4) +
    geom_vline(xintercept = 0, linetype = 'dashed')
Picking joint bandwidth of 0.0267

##Or on a fractional scale
day.brm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges_gradient(aes(x=exp(.value),
                                     y = .variable,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_c(option = "C")
Picking joint bandwidth of 0.0386

This is purely a graphical depiction on the posteriors.

day.brm3 |> tidy_draws()
# A tibble: 2,400 × 17
   .chain .iteration .draw b_Intercept b_TREATALG2 b_TREATNB b_TREATS
    <int>      <int> <int>       <dbl>       <dbl>     <dbl>    <dbl>
 1      1          1     1        3.14      0.255     -0.612   -0.630
 2      1          2     2        2.99      0.373     -0.149   -0.455
 3      1          3     3        3.11      0.284     -0.448   -0.587
 4      1          4     4        2.94      0.420     -0.105   -0.391
 5      1          5     5        3.01      0.239     -0.224   -0.478
 6      1          6     6        2.93      0.429     -0.229   -0.465
 7      1          7     7        3.07      0.214     -0.350   -0.470
 8      1          8     8        3.14      0.307     -0.405   -0.446
 9      1          9     9        3.24     -0.0957    -0.614   -0.850
10      1         10    10        3.11      0.219     -0.386   -0.495
# ℹ 2,390 more rows
# ℹ 10 more variables: prior_Intercept <dbl>, prior_b <dbl>, lprior <dbl>,
#   lp__ <dbl>, accept_stat__ <dbl>, treedepth__ <dbl>, stepsize__ <dbl>,
#   divergent__ <dbl>, n_leapfrog__ <dbl>, energy__ <dbl>
day.brm3 |> spread_draws(`.Intercept.*|.*TREAT.*`,  regex=TRUE)
# A tibble: 2,400 × 6
   .chain .iteration .draw b_TREATALG2 b_TREATNB b_TREATS
    <int>      <int> <int>       <dbl>     <dbl>    <dbl>
 1      1          1     1      0.255     -0.612   -0.630
 2      1          2     2      0.373     -0.149   -0.455
 3      1          3     3      0.284     -0.448   -0.587
 4      1          4     4      0.420     -0.105   -0.391
 5      1          5     5      0.239     -0.224   -0.478
 6      1          6     6      0.429     -0.229   -0.465
 7      1          7     7      0.214     -0.350   -0.470
 8      1          8     8      0.307     -0.405   -0.446
 9      1          9     9     -0.0957    -0.614   -0.850
10      1         10    10      0.219     -0.386   -0.495
# ℹ 2,390 more rows
day.brm3 |> posterior_samples() |> as_tibble()
Warning: Method 'posterior_samples' is deprecated. Please see ?as_draws for
recommended alternatives.
# A tibble: 2,400 × 8
   b_Intercept b_TREATALG2 b_TREATNB b_TREATS prior_Intercept prior_b lprior
         <dbl>       <dbl>     <dbl>    <dbl>           <dbl>   <dbl>  <dbl>
 1        3.14      0.255     -0.612   -0.630          -0.230  -1.33   -7.17
 2        2.99      0.373     -0.149   -0.455           5.45   -1.21   -7.13
 3        3.11      0.284     -0.448   -0.587           5.42   -3.34   -7.15
 4        2.94      0.420     -0.105   -0.391           2.03    2.10   -7.12
 5        3.01      0.239     -0.224   -0.478           2.00    0.543  -7.12
 6        2.93      0.429     -0.229   -0.465           4.59   -3.19   -7.14
 7        3.07      0.214     -0.350   -0.470           4.75    0.917  -7.13
 8        3.14      0.307     -0.405   -0.446          -1.08    2.02   -7.13
 9        3.24     -0.0957    -0.614   -0.850           3.66    2.59   -7.19
10        3.11      0.219     -0.386   -0.495           5.11    4.63   -7.13
# ℹ 2,390 more rows
# ℹ 1 more variable: lp__ <dbl>
day.brm3 |> bayes_R2(summary=FALSE) |> median_hdci()
          y      ymin      ymax .width .point .interval
1 0.7005221 0.5195665 0.7762791   0.95 median      hdci

Region of Practical Equivalence

0.1 * sd(log(day$BARNACLE))
[1] 0.04111272
day.brm3 |> rope(range = c(-0.04, 0.04))
# Proportion of samples inside the ROPE [-0.04, 0.04]:

Parameter | inside ROPE
-----------------------
Intercept |      0.00 %
TREATALG2 |      2.76 %
TREATNB   |      0.00 %
TREATS    |      0.00 %
rope(day.brm3, range = c(-0.04, 0.04)) |> plot()

## Or based on fractional scale
day.brm3 |>
    as_draws_df('^b_TREAT.*', regex = TRUE) |>
    exp() |> 
    ## equivalence_test(range = c(0.9, 1.1))
    rope(range = c(0.9, 1.1))
# Proportion of samples inside the ROPE [0.90, 1.10]:

Parameter | inside ROPE
-----------------------
TREATALG2 |     10.18 %
TREATNB   |      0.00 %
TREATS    |      0.00 %
day.mcmc <-
    day.brm3 |> as_draws_df('^b_TREAT.*', regex = TRUE) |>
    exp()
day.mcmc |>
    rope(range = c(0.9, 1.1))
# Proportion of samples inside the ROPE [0.90, 1.10]:

Parameter | inside ROPE
-----------------------
TREATALG2 |     10.18 %
TREATNB   |      0.00 %
TREATS    |      0.00 %
day.mcmc |>
    rope(range = c(0.9, 1.1)) |>
    plot(day.mcmc)

day.mcmc |>
    equivalence_test(range = c(0.9, 1.1)) 
# Test for Practical Equivalence

  ROPE: [0.90 1.10]

Parameter |        H0 | inside ROPE |     95% HDI
-------------------------------------------------
TREATALG2 | Undecided |     10.18 % | [0.99 1.63]
TREATNB   |  Rejected |      0.00 % | [0.50 0.89]
TREATS    |  Rejected |      0.00 % | [0.43 0.79]

10 Further investigations

day.rstanarm3 |> emmeans(pairwise ~TREAT, type='response')
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.
$emmeans
 TREAT rate lower.HPD upper.HPD
 ALG1  22.1      18.4      26.2
 ALG2  28.2      23.6      32.5
 NB    15.0      11.5      18.3
 S     13.3      10.1      16.4

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 

$contrasts
 contrast    ratio lower.HPD upper.HPD
 ALG1 / ALG2 0.782     0.617     0.995
 ALG1 / NB   1.473     1.068     1.948
 ALG1 / S    1.683     1.211     2.196
 ALG2 / NB   1.882     1.429     2.484
 ALG2 / S    2.132     1.533     2.794
 NB / S      1.133     0.792     1.551

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.

Conclusions:

  • the contrasts section of the output indicates that there is evidence of:
  • ALG1 has 1.47 fold (47%) more newly recruited barnacles than the NB substrate
  • ALG1 has 1.68 fold (68%) more newly recruited barnacles than the S substrate
  • ALG2 has 1.88 fold (88%) more newly recruited barnacles than the NB substrate
  • ALG2 has 2.13 fold (113%) more newly recruited barnacles than the S substrate
  • ALG1 was not found to be different to ALG2 and NB was not found to be different to S
day.em = emmeans(day.rstanarm3, pairwise~TREAT, type='link')$contrasts |>
    gather_emmeans_draws() |>
    mutate(Fit=exp(.value))
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.
day.em |> head()
# A tibble: 6 × 6
# Groups:   contrast [1]
  contrast    .chain .iteration .draw .value   Fit
  <chr>        <int>      <int> <int>  <dbl> <dbl>
1 ALG1 - ALG2     NA         NA     1 -0.184 0.832
2 ALG1 - ALG2     NA         NA     2 -0.260 0.771
3 ALG1 - ALG2     NA         NA     3 -0.410 0.663
4 ALG1 - ALG2     NA         NA     4 -0.236 0.789
5 ALG1 - ALG2     NA         NA     5 -0.213 0.808
6 ALG1 - ALG2     NA         NA     6 -0.405 0.667
day.em |> group_by(contrast) |>
    ggplot(aes(x=Fit)) +
    geom_histogram() +
    geom_vline(xintercept=1, color='red') + 
    facet_wrap(~contrast, scales='free')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

day.em |> group_by(contrast) |>
    ggplot(aes(x=Fit)) +
    geom_density_ridges_gradient(aes(y = contrast, fill = stat(x)),
                                 alpha = 0.4, color = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept=1, linetype = 'dashed') +
    scale_fill_viridis_c(option = "C") +
    scale_x_continuous(trans = scales::log2_trans())
Warning: `stat(x)` was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(x)` instead.
Picking joint bandwidth of 0.0405
Warning: Using the `size` aesthetic with geom_segment was deprecated in ggplot2 3.4.0.
ℹ Please use the `linewidth` aesthetic instead.

day.em |> 
  ggplot(aes(x = Fit)) + 
    geom_density_ridges_gradient(aes(y = contrast,
                                     fill = factor(stat(x>0))),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_d()
Picking joint bandwidth of 0.0405

day.em |> group_by(contrast) |> median_hdi()
# A tibble: 6 × 10
  contrast    .value .value.lower .value.upper   Fit Fit.lower Fit.upper .width
  <chr>        <dbl>        <dbl>        <dbl> <dbl>     <dbl>     <dbl>  <dbl>
1 ALG1 - ALG2 -0.246      -0.478      0.000988 0.782     0.617     0.995   0.95
2 ALG1 - NB    0.388       0.0961     0.693    1.47      1.07      1.95    0.95
3 ALG1 - S     0.520       0.192      0.787    1.68      1.21      2.20    0.95
4 ALG2 - NB    0.632       0.360      0.912    1.88      1.43      2.48    0.95
5 ALG2 - S     0.757       0.491      1.07     2.13      1.53      2.79    0.95
6 NB - S       0.125      -0.213      0.452    1.13      0.792     1.55    0.95
# ℹ 2 more variables: .point <chr>, .interval <chr>
# Probability of effect
day.em |> group_by(contrast) |> summarize(P=mean(Fit>1))
# A tibble: 6 × 2
  contrast         P
  <chr>        <dbl>
1 ALG1 - ALG2 0.0242
2 ALG1 - NB   0.998 
3 ALG1 - S    1.00  
4 ALG2 - NB   1     
5 ALG2 - S    1     
6 NB - S      0.770 
day.em |> group_by(contrast) |> summarize(P=mean(Fit<1))
# A tibble: 6 × 2
  contrast           P
  <chr>          <dbl>
1 ALG1 - ALG2 0.976   
2 ALG1 - NB   0.0025  
3 ALG1 - S    0.000417
4 ALG2 - NB   0       
5 ALG2 - S    0       
6 NB - S      0.230   
##Probability of effect greater than 10%
day.em |> group_by(contrast) |> summarize(P=mean(Fit>1.1))
# A tibble: 6 × 2
  contrast          P
  <chr>         <dbl>
1 ALG1 - ALG2 0.00125
2 ALG1 - NB   0.979  
3 ALG1 - S    0.997  
4 ALG2 - NB   1      
5 ALG2 - S    1      
6 NB - S      0.572  
day.brm3 |>
    emmeans(~TREAT, type = 'response') |>
    pairs()
 contrast    ratio lower.HPD upper.HPD
 ALG1 / ALG2 0.786     0.599     0.986
 ALG1 / NB   1.497     1.099     1.966
 ALG1 / S    1.695     1.218     2.258
 ALG2 / NB   1.901     1.394     2.474
 ALG2 / S    2.164     1.574     2.845
 NB / S      1.135     0.748     1.515

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
#OR
day.pairwise <- day.brm3 |>
    emmeans(~TREAT, type = 'response') |>
    pairs() |>
    as.data.frame()
##OR
day.brm3 |>
    emmeans(~TREAT) |>
    pairs() |>
    tidy_draws() |>
    exp() |>
    summarise_draws(median)
# A tibble: 6 × 2
  variable             median
  <chr>                 <num>
1 contrast ALG1 - ALG2  0.786
2 contrast ALG1 - NB    1.50 
3 contrast ALG1 - S     1.70 
4 contrast ALG2 - NB    1.90 
5 contrast ALG2 - S     2.16 
6 contrast NB - S       1.14 
##OR
day.brm3 |>
    emmeans(~TREAT) |>
    pairs() |>
    gather_emmeans_draws() |>
    mutate(.ratio = exp(.value)) |>
    ## median_hdci(.ratio)
    summarise(
        median_hdci(.ratio),
        P = mean(.ratio>1),
        ROPE = rope(.ratio, range = c(0.9, 1.1))$ROPE_Percentage)
# A tibble: 6 × 9
  contrast        y  ymin  ymax .width .point .interval      P  ROPE
  <chr>       <dbl> <dbl> <dbl>  <dbl> <chr>  <chr>      <dbl> <dbl>
1 ALG1 - ALG2 0.786 0.599 0.986   0.95 median hdci      0.0279 0.119
2 ALG1 - NB   1.50  1.10  1.97    0.95 median hdci      0.998  0    
3 ALG1 - S    1.70  1.22  2.26    0.95 median hdci      1      0    
4 ALG2 - NB   1.90  1.39  2.47    0.95 median hdci      1      0    
5 ALG2 - S    2.16  1.57  2.85    0.95 median hdci      1      0    
6 NB - S      1.14  0.748 1.51    0.95 median hdci      0.782  0.357
    ## summarise(across(c(.value, .ratio), c(median, HDInterval::hdi)))
    ## summarise(across(c(.value, .ratio), c(median_hdci)))

day.mcmc <-
    day.brm3 |>
    emmeans(~TREAT) |>
    pairs() |>
    tidy_draws() |>
    dplyr::select(-.chain, -.iteration, -.draw) |>
    exp() 
rope(day.mcmc, range = c(0.9, 1.1)) |> plot()

Conclusions:

  • the contrasts section of the output indicates that there is evidence of:
  • ALG1 has 1.5 fold (50%) more newly recruited barnacles than the NB substrate
  • ALG1 has 1.7 fold (70%) more newly recruited barnacles than the S substrate
  • ALG2 has 1.9 fold (90%) more newly recruited barnacles than the NB substrate
  • ALG2 has 2.16 fold (116%) more newly recruited barnacles than the S substrate
  • ALG1 was not found to be different to ALG2 and NB was not found to be different to S
day.brm3 |> emmeans(~TREAT, type = 'response') |>
    pairs()
 contrast    ratio lower.HPD upper.HPD
 ALG1 / ALG2 0.786     0.599     0.986
 ALG1 / NB   1.497     1.099     1.966
 ALG1 / S    1.695     1.218     2.258
 ALG2 / NB   1.901     1.394     2.474
 ALG2 / S    2.164     1.574     2.845
 NB / S      1.135     0.748     1.515

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
day.em <- day.brm3 |>
    emmeans(~TREAT, type = 'link') |>
    pairs() |>
    gather_emmeans_draws() |>
    mutate(Fit = exp(.value))
day.em |> group_by(contrast) |>
    ggplot(aes(x=Fit)) +
    geom_density_ridges_gradient(aes(y = contrast, fill = stat(x)),
                                 alpha = 0.4, color = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept=1, linetype = 'dashed') +
    scale_fill_viridis_c(option = "C") +
    scale_x_continuous(trans = scales::log2_trans())
Picking joint bandwidth of 0.0407

day.em |> 
  ggplot(aes(x = Fit)) + 
    geom_density_ridges_gradient(aes(y = contrast,
                                     fill = factor(stat(x>0))),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_d() +
    scale_x_continuous(trans = scales::log2_trans())
Scale for x is already present.
Adding another scale for x, which will replace the existing scale.
Picking joint bandwidth of 0.0407

day.em |> head()
# A tibble: 6 × 6
# Groups:   contrast [1]
  contrast    .chain .iteration .draw .value   Fit
  <chr>        <int>      <int> <int>  <dbl> <dbl>
1 ALG1 - ALG2     NA         NA     1 -0.255 0.775
2 ALG1 - ALG2     NA         NA     2 -0.373 0.689
3 ALG1 - ALG2     NA         NA     3 -0.284 0.753
4 ALG1 - ALG2     NA         NA     4 -0.420 0.657
5 ALG1 - ALG2     NA         NA     5 -0.239 0.787
6 ALG1 - ALG2     NA         NA     6 -0.429 0.651
day.em |>
    group_by(contrast) |>
    ggplot(aes(x = Fit)) +
    ## geom_histogram() +
    geom_halfeyeh() +
    geom_vline(xintercept = 1, color = 'red') + 
    facet_wrap(~contrast, scales = 'free')
Warning: 'geom_halfeyeh' is deprecated.
Use 'stat_halfeye' instead.
See help("Deprecated") and help("tidybayes-deprecated").

day.em |>
    group_by(contrast) |>
    median_hdi()
# A tibble: 6 × 10
  contrast    .value .value.lower .value.upper   Fit Fit.lower Fit.upper .width
  <chr>        <dbl>        <dbl>        <dbl> <dbl>     <dbl>     <dbl>  <dbl>
1 ALG1 - ALG2 -0.241       -0.475       0.0204 0.786     0.599     0.986   0.95
2 ALG1 - NB    0.404        0.145       0.716  1.50      1.10      1.97    0.95
3 ALG1 - S     0.528        0.239       0.848  1.70      1.22      2.26    0.95
4 ALG2 - NB    0.642        0.379       0.950  1.90      1.39      2.47    0.95
5 ALG2 - S     0.772        0.482       1.07   2.16      1.57      2.85    0.95
6 NB - S       0.127       -0.211       0.462  1.14      0.748     1.51    0.95
# ℹ 2 more variables: .point <chr>, .interval <chr>
# Probability of effect
day.em |> group_by(contrast) |> summarize(P = mean(Fit>1))
# A tibble: 6 × 2
  contrast         P
  <chr>        <dbl>
1 ALG1 - ALG2 0.0279
2 ALG1 - NB   0.998 
3 ALG1 - S    1     
4 ALG2 - NB   1     
5 ALG2 - S    1     
6 NB - S      0.782 
##Probability of effect greater than 10%
day.em |> group_by(contrast) |> summarize(P = mean(Fit>1.1))
# A tibble: 6 × 2
  contrast          P
  <chr>         <dbl>
1 ALG1 - ALG2 0.00375
2 ALG1 - NB   0.983  
3 ALG1 - S    0.998  
4 ALG2 - NB   1      
5 ALG2 - S    1      
6 NB - S      0.575  
## Effect size on absolute scale
day.em <- day.brm3 |>
    emmeans(~TREAT, type = 'link') |>
    regrid() |>
    pairs() |>
    gather_emmeans_draws() |>
    median_hdci(.value)

day.brm3 |>
    emmeans(~TREAT, type = 'link') |>
    regrid() |>
    pairs() |>
    gather_emmeans_draws() |>
    group_by(contrast) |>
    ggplot(aes(x = .value)) +
    geom_halfeyeh() +
    geom_vline(xintercept = 0, color = 'red') + 
    facet_wrap(~contrast, scales = 'free')
Warning: 'geom_halfeyeh' is deprecated.
Use 'stat_halfeye' instead.
See help("Deprecated") and help("tidybayes-deprecated").

day.brm3 |>
    emmeans(~TREAT, type = 'response') |>
    pairs() |>
    gather_emmeans_draws() |>
    mutate(.value = exp(.value)) |>
    ggplot(aes(x = .value)) + 
    geom_density_ridges_gradient(aes(y = contrast,
                                     fill = factor(stat(x>0))),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_d() 
Picking joint bandwidth of 0.0407

Define your own

Compare:

  1. ALG1 vs ALG2
  2. NB vs S
  3. average of ALG1+ALG2 vs NB+S
Levels Alg1 vs Alg2 NB vs S Alg vs Bare
Alg1 1 0 0.5
Alg2 -1 0 0.5
NB 0 1 -0.5
S 0 -1 -0.5
##Planned contrasts
cmat<-cbind('Alg2_Alg1'=c(-1,1,0,0),
              'NB_S'=c(0,0,1,-1),
             'Alg_Bare'=c(0.5,0.5,-0.5,-0.5),
             'Alg_NB'=c(0.5,0.5,-1,0))
# On the link scale
emmeans(day.rstanarm3, ~TREAT, contr=list(TREAT=cmat), type='link')
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.
$emmeans
 TREAT emmean lower.HPD upper.HPD
 ALG1    3.10      2.92      3.28
 ALG2    3.34      3.18      3.50
 NB      2.71      2.46      2.92
 S       2.59      2.34      2.83

Point estimate displayed: median 
Results are given on the log (not the response) scale. 
HPD interval probability: 0.95 

$contrasts
 contrast        estimate lower.HPD upper.HPD
 TREAT.Alg2_Alg1    0.246 -0.000988     0.478
 TREAT.NB_S         0.125 -0.212872     0.452
 TREAT.Alg_Bare     0.575  0.355709     0.769
 TREAT.Alg_NB       0.507  0.269481     0.789

Point estimate displayed: median 
Results are given on the log (not the response) scale. 
HPD interval probability: 0.95 
# On the response scale
emmeans(day.rstanarm3, ~TREAT, contr=list(TREAT=cmat), type='response')
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.
$emmeans
 TREAT rate lower.HPD upper.HPD
 ALG1  22.1      18.4      26.2
 ALG2  28.2      23.6      32.5
 NB    15.0      11.5      18.3
 S     13.3      10.1      16.4

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 

$contrasts
 contrast        ratio lower.HPD upper.HPD
 TREAT.Alg2_Alg1  1.28     0.974      1.58
 TREAT.NB_S       1.13     0.792      1.55
 TREAT.Alg_Bare   1.78     1.424      2.15
 TREAT.Alg_NB     1.66     1.295      2.18

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
day.em = emmeans(day.rstanarm3, ~TREAT, contr=list(TREAT=cmat), type='link')$contrasts |>
      gather_emmeans_draws() |> mutate(Fit=exp(.value)) 
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.
day.em |> group_by(contrast) |> mean_hdi()
# A tibble: 4 × 10
  contrast     .value .value.lower .value.upper   Fit Fit.lower Fit.upper .width
  <chr>         <dbl>        <dbl>        <dbl> <dbl>     <dbl>     <dbl>  <dbl>
1 TREAT.Alg2_…  0.243    -0.000988        0.478  1.28     0.974      1.58   0.95
2 TREAT.Alg_B…  0.575     0.356           0.769  1.79     1.42       2.15   0.95
3 TREAT.Alg_NB  0.513     0.269           0.789  1.68     1.29       2.18   0.95
4 TREAT.NB_S    0.125    -0.213           0.452  1.15     0.792      1.55   0.95
# ℹ 2 more variables: .point <chr>, .interval <chr>
# Probability of effect
day.em |> group_by(contrast) |> summarize(P=mean(Fit>1))
# A tibble: 4 × 2
  contrast            P
  <chr>           <dbl>
1 TREAT.Alg2_Alg1 0.976
2 TREAT.Alg_Bare  1    
3 TREAT.Alg_NB    1    
4 TREAT.NB_S      0.770
##Probability of effect greater than 10%
day.em |> group_by(contrast) |> summarize(P=mean(Fit>1.5))
# A tibble: 4 × 2
  contrast             P
  <chr>            <dbl>
1 TREAT.Alg2_Alg1 0.0833
2 TREAT.Alg_Bare  0.945 
3 TREAT.Alg_NB    0.788 
4 TREAT.NB_S      0.0529
day.sum <- day.em |>
  group_by(contrast) |>
  median_hdci(.width=c(0.8, 0.95))
day.sum
# A tibble: 8 × 10
  contrast     .value .value.lower .value.upper   Fit Fit.lower Fit.upper .width
  <chr>         <dbl>        <dbl>        <dbl> <dbl>     <dbl>     <dbl>  <dbl>
1 TREAT.Alg2_…  0.246     0.0948          0.403  1.28     1.08       1.47   0.8 
2 TREAT.Alg_B…  0.575     0.443           0.713  1.78     1.53       2.01   0.8 
3 TREAT.Alg_NB  0.507     0.325           0.670  1.66     1.38       1.95   0.8 
4 TREAT.NB_S    0.125    -0.123           0.323  1.13     0.883      1.38   0.8 
5 TREAT.Alg2_…  0.246    -0.000988        0.478  1.28     0.974      1.58   0.95
6 TREAT.Alg_B…  0.575     0.356           0.769  1.78     1.42       2.15   0.95
7 TREAT.Alg_NB  0.507     0.269           0.789  1.66     1.29       2.18   0.95
8 TREAT.NB_S    0.125    -0.213           0.452  1.13     0.792      1.55   0.95
# ℹ 2 more variables: .point <chr>, .interval <chr>
ggplot(day.sum) +
  geom_hline(yintercept=1, linetype='dashed') +
  geom_pointrange(aes(x=contrast, y=Fit, ymin=Fit.lower, ymax=Fit.upper, size=factor(.width)),
                  show.legend = FALSE) +
  scale_size_manual(values=c(1, 0.5)) +
  coord_flip()

g1 <- ggplot(day.sum) +
  geom_hline(yintercept=1) +
  geom_pointrange(aes(x=contrast, y=Fit, ymin=Fit.lower, ymax=Fit.upper, size=factor(.width)), show.legend = FALSE) +
  scale_size_manual(values=c(1, 0.5)) +
  scale_y_continuous(trans=scales::log2_trans(),  breaks=c(0.5, 1, 2, 4)) +
  coord_flip() + 
  theme_classic()
g1   

##Planned contrasts
cmat<-cbind('Alg2_Alg1' = c(-1,1,0,0),
            'NB_S' = c(0,0,1,-1),
            'Alg_Bare' = c(0.5,0.5,-0.5,-0.5),
            'Alg_NB' = c(0.5,0.5,-1,0))
# On the link scale
day.brm3 |> emmeans(~TREAT, type = 'link') |>
    contrast(method = list(TREAT = cmat))
 contrast        estimate lower.HPD upper.HPD
 TREAT.Alg2_Alg1    0.241   -0.0204     0.475
 TREAT.NB_S         0.127   -0.2110     0.462
 TREAT.Alg_Bare     0.588    0.3721     0.793
 TREAT.Alg_NB       0.520    0.2707     0.782

Point estimate displayed: median 
Results are given on the log (not the response) scale. 
HPD interval probability: 0.95 
# On the response scale
day.brm3 |>
    emmeans(~TREAT, type = 'response') |>
    contrast(method = list(TREAT = cmat))
 contrast        ratio lower.HPD upper.HPD
 TREAT.Alg2_Alg1  1.27     0.971      1.60
 TREAT.NB_S       1.14     0.748      1.51
 TREAT.Alg_Bare   1.80     1.431      2.19
 TREAT.Alg_NB     1.68     1.291      2.16

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
day.em <- day.brm3 |>
    emmeans(~TREAT, type = 'link') |>
    contrast(method = list(TREAT = cmat)) |>
    gather_emmeans_draws() |>
    mutate(Fit = exp(.value)) 
day.em |> median_hdi(Fit)
# A tibble: 4 × 7
  contrast          Fit .lower .upper .width .point .interval
  <chr>           <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 TREAT.Alg2_Alg1  1.27  0.971   1.60   0.95 median hdi      
2 TREAT.Alg_Bare   1.80  1.43    2.19   0.95 median hdi      
3 TREAT.Alg_NB     1.68  1.29    2.16   0.95 median hdi      
4 TREAT.NB_S       1.14  0.748   1.51   0.95 median hdi      
# Probability of effect
day.em |> summarize(P = mean(Fit>1))
# A tibble: 4 × 2
  contrast            P
  <chr>           <dbl>
1 TREAT.Alg2_Alg1 0.972
2 TREAT.Alg_Bare  1    
3 TREAT.Alg_NB    1    
4 TREAT.NB_S      0.782
##Probability of effect greater than 50%
day.em |> summarize(P = mean(Fit>1.5))
# A tibble: 4 × 2
  contrast             P
  <chr>            <dbl>
1 TREAT.Alg2_Alg1 0.0958
2 TREAT.Alg_Bare  0.959 
3 TREAT.Alg_NB    0.815 
4 TREAT.NB_S      0.05  
day.sum <- day.em |>
  group_by(contrast) |>
  median_hdci(.value, .width = c(0.8, 0.95))
day.sum
# A tibble: 8 × 7
  contrast        .value  .lower .upper .width .point .interval
  <chr>            <dbl>   <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 TREAT.Alg2_Alg1  0.241  0.0914  0.411   0.8  median hdci     
2 TREAT.Alg_Bare   0.588  0.455   0.726   0.8  median hdci     
3 TREAT.Alg_NB     0.520  0.348   0.688   0.8  median hdci     
4 TREAT.NB_S       0.127 -0.101   0.327   0.8  median hdci     
5 TREAT.Alg2_Alg1  0.241 -0.0204  0.475   0.95 median hdci     
6 TREAT.Alg_Bare   0.588  0.372   0.793   0.95 median hdci     
7 TREAT.Alg_NB     0.520  0.271   0.782   0.95 median hdci     
8 TREAT.NB_S       0.127 -0.211   0.462   0.95 median hdci     
g1 <- ggplot(day.sum) +
  geom_vline(xintercept = 0, linetype = 'dashed') +
  geom_pointrange(aes(y = contrast, x = .value, xmin = .lower, xmax = .upper,
                      size = factor(.width)),
                  show.legend  =  FALSE) +
  scale_size_manual(values = c(1, 0.5)) 

day.sum <- day.em |>
  group_by(contrast) |>
  median_hdci(Fit, .width = c(0.8, 0.95))
day.sum
# A tibble: 8 × 7
  contrast          Fit .lower .upper .width .point .interval
  <chr>           <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 TREAT.Alg2_Alg1  1.27  1.06    1.47   0.8  median hdci     
2 TREAT.Alg_Bare   1.80  1.56    2.05   0.8  median hdci     
3 TREAT.Alg_NB     1.68  1.37    1.94   0.8  median hdci     
4 TREAT.NB_S       1.14  0.890   1.37   0.8  median hdci     
5 TREAT.Alg2_Alg1  1.27  0.971   1.60   0.95 median hdci     
6 TREAT.Alg_Bare   1.80  1.43    2.19   0.95 median hdci     
7 TREAT.Alg_NB     1.68  1.29    2.16   0.95 median hdci     
8 TREAT.NB_S       1.14  0.748   1.51   0.95 median hdci     
g1 <- ggplot(day.sum) +
  geom_vline(xintercept = 1, linetype='dashed') +
  geom_pointrange(aes(y = contrast, x = Fit, xmin = .lower, xmax = .upper, size = factor(.width)), show.legend = FALSE) +
  scale_size_manual(values = c(1, 0.5)) +
  scale_x_continuous(trans = scales::log2_trans(),  breaks = c(0.5, 0.8,1,1.2, 1.5, 2, 4)) +
  theme_classic()
g1   

g1a <- 
    day.em |>
    ggplot() +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    #geom_vline(xintercept = 1.5, alpha=0.3, linetype = 'dashed') +
    stat_slab(aes(x = Fit, y = contrast,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                            .width = c(0.5, 0.8, 0.95), 
                            labels = scales::percent_format())
                            )), color = 'black') +
    scale_fill_brewer('Interval', direction  =  -1, na.translate = FALSE) +
    scale_x_continuous('Effect', trans = scales::log2_trans(),
                       breaks = c(0.5, 0.8,1,1.2, 1.5, 2, 4)) +
    scale_y_discrete('', breaks=c('TREAT.NB_S', 'TREAT.Alg2_Alg1', 'TREAT.Alg_NB', 'TREAT.Alg_Bare'),
                     labels = c('Nat. Bare vs Scapped', 'Algae 1 vs 2', 'Algae vs Nat. Bare', 'Algae vs Bare')) +
    theme_classic()
g1 + g1a

library(ggridges)
day.em |>
  ggplot() + 
    geom_density_ridges(aes(x=Fit, y = contrast), alpha=0.4) +
    geom_vline(xintercept = 1, linetype = 'dashed')
Picking joint bandwidth of 0.0367

day.em |>
  ggplot() + 
    geom_density_ridges_gradient(aes(x=Fit,
                                     y = contrast,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_c(option = "C")
Picking joint bandwidth of 0.0365

day.em |>
  ggplot() + 
    geom_density_ridges_gradient(aes(x=100*(Fit-1),
                                     y = contrast,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous('Percentage change') +
    scale_fill_viridis_c(option = "C")
Picking joint bandwidth of 3.67

##Or on a fractional scale
day.brm3 |> 
  gather_draws(`.*TREAT.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges_gradient(aes(x=exp(.value),
                                     y = .variable,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_c(option = "C")
Picking joint bandwidth of 0.0386

11 Summary Figure

newdata = emmeans(day.rstanarm3, ~TREAT, type='response') |>
    as.data.frame()
Warning: Model has 0 prior weights, but we recovered 20 rows of data.
So prior weights were ignored.
newdata
 TREAT     rate lower.HPD upper.HPD
 ALG1  22.11969  18.35349  26.23568
 ALG2  28.24340  23.55377  32.54169
 NB    15.02473  11.50381  18.26040
 S     13.27201  10.07453  16.38795

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
## A quick version
g2 <- ggplot(newdata, aes(y=rate, x=TREAT)) +
    geom_pointrange(aes(ymin=lower.HPD, ymax=upper.HPD)) +
    theme_classic()
    
g2 + g1    

newdata <- day.brm3 |>
    emmeans(~TREAT, type='response') |>
    as.data.frame()
newdata
 TREAT     rate lower.HPD upper.HPD
 ALG1  22.38173 18.435903  26.37351
 ALG2  28.42284 23.859083  32.90202
 NB    14.96582 11.670940  18.47148
 S     13.13527  9.940735  16.33616

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
## A quick version
g2 <- ggplot(newdata, aes(y=rate, x=TREAT)) +
    geom_pointrange(aes(ymin=lower.HPD, ymax=upper.HPD)) +
    scale_y_continuous('Number of newly recruited barnacles') +
    scale_x_discrete('', breaks=c('ALG1', 'ALG2', 'NB', 'S'),
                     labels = c('Algae 1', 'Algae 2', 'Nat. Bare', 'Scraped')) +
    theme_classic()
    
g2 + g1    

(g2 + ggtitle('a)')) + (g1a + ggtitle('b)'))    

12 References

Quinn, G. P., and K. J. Keough. 2002. Experimental Design and Data Analysis for Biologists. London: Cambridge University Press.